<template>
  <a-modal v-model:visible="visible" :align-center="false" title-align="start" :width="800" draggable>
    <template #title>收件人地址</template>
    <a-form ref="formDataRef" :model="formData" :style="{ width: '600px' }">
      <a-form-item field="name" label="收件人" :rules="[REQUIRED, VARCHAR20]">
        <a-input v-model="formData.name" placeholder="请输入收件人姓名"></a-input>
      </a-form-item>
      <a-form-item field="address" label="收件地区" :rules="[REQUIRED]">
        <span>{{ formData.address || '暂无地址' }}</span>
        <a-button @click="openAddress()" size="mini" type="outline" status="danger" class="ml_10">选择</a-button>
      </a-form-item>
      <a-form-item field="detail" label="详细地址" :rules="[REQUIRED]">
        <a-input v-model="formData.detail" placeholder="请输入详细地址"></a-input>
      </a-form-item>
      <a-form-item field="mobile" label="手机号码" :rules="[REQUIRED, MOBILE]">
        <a-input v-model="formData.mobile" placeholder="请输入收件人手机号码" :max-length="11"></a-input>
      </a-form-item>
      <a-form-item field="alias" label="地址别名">
        <a-input v-model="formData.alias" placeholder="请输入地址别名，例如公司"></a-input>
      </a-form-item>
      <a-form-item field="isRead" label="默认地址">
        <a-switch v-model="formData.isDefault" checked-color="#ef4444"></a-switch>
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="text-align: right">
        <a-button @click="close">取消</a-button>
        <a-button class="ml_10" type="primary" @click="handleSubmit" :loading="loading">保存收货地址</a-button>
      </div>
    </template>
    <!--选择地址-->
    <MultipleMap ref="multipleMap" @callback="getAddress"></MultipleMap>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { REQUIRED, VARCHAR20, MOBILE } from '@/utils/validator';
  import { newMemberAddress, editMemberAddress, getAddrDetail } from "@/api/address";

  const visible = ref(false); // 是否可见
  const multipleMap = ref();
  const formDataRef = ref();
  // 添加地址表单
  const formData = ref<any>({
    address: '',
    consigneeAddressIdPath: '',
    lat: '',
    lon: '',
  });
  const loading = ref(false);
  const addressId = ref(null);
  const emit = defineEmits<{
    (e: 'callback', val: any): void;
  }>();

  const openAddress = () => {
    if (multipleMap.value) {
      multipleMap.value.open();
    }
  };
  // 选择地址回调
  const getAddress = (val: any) => {
    if(val.type === 'select'){
      const paths = val.data.map((item: any) => item.name).join(',');
      const ids = val.data.map((item: any) => item.id).join(',');
      formData.value.address = paths;
      formData.value.consigneeAddressIdPath = ids;
      const coord = val.data[val.data.length - 1].center.split(',');
      formData.value.lat = coord[1];
      formData.value.lon = coord[0];
    }
  };
  // 保存收货地址
  const handleSubmit = async () => {
    const auth = await formDataRef.value?.validate();
    if (!auth) {
      const params = JSON.parse(JSON.stringify(formData.value));
      params.consigneeAddressPath = params.address.replace(/\s/g, ",");
      delete params.address;
      loading.value = true;
      if (addressId.value) {
        editMemberAddress(params).then((res) => {
          if (res.data.success) {
            loading.value = false;
            Message.success('编辑地址成功！');
            close();
            emit('callback', true);
          }
        }).catch(() => {
          loading.value = false;
        });
      } else {
        newMemberAddress(params).then((res) => {
          if (res.data.success) {
            loading.value = false;
            Message.success('新增地址成功！');
            close();
            emit('callback', true);
          }
        }).catch(() => {
          loading.value = false;
        });
      }
    }
  };
  // 取消
  const close = () => {
    visible.value = false;
  };
  // 获取地址详情
  const getAddrById = (id: any) => {
    getAddrDetail(id).then((res) => {
      if (res.data.success) {
        const data = res.data.result;
        data.address = res.data.result.consigneeAddressPath.replace(/,/g, " ");
        formData.value = data;
      }
    });
  };
  // 初始化内容
  const init = (id: any) => {
    addressId.value = id;
    if (addressId.value) {
      getAddrById(addressId.value);
    } else {
      formData.value = {};
    }
    visible.value = true;
  };
  // 暴露方法变量
  defineExpose({
    init,
    close
  });
</script>

<style scoped lang="less">




</style>
